package com.xiaohei.common.JWT;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * ClassName: JWTHelper
 * Package:
 * Description:
 *
 * @Author:xiaohei
 * @Create 2024/4/29 20:54
 * Version 1.0
 */

//JWT工具类
public class JWTHelper {
    private static long tokenExpiration = 365 * 24 * 60 * 60 * 1000;
    private static String tokenSignKey = "123456";

    public static String createToken(Long userId, String username) {
        String token = Jwts.builder()
                //分类
                .setSubject("AUTH-USER")
                //设置token的有效时间
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                //JWT的主体部分
                .claim("userId", userId)
                .claim("username", username)
                //设置签名部分
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                //对生成的字符串进行压缩
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }

    //获取用户id
    public static Long getUserId(String token) {
        try {
            if (StringUtils.isEmpty(token)) {
                return null;
            }

            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            Integer userId = (Integer) claims.get("userId");
            return userId.longValue();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //获取用户名称
    public static String getUsername(String token) {
        try {
            if (StringUtils.isEmpty(token)) {
                return "";
            }

            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return (String) claims.get("username");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        String token = JWTHelper.createToken(1L,"admin");
        System.out.println(token);
        Long userId = JWTHelper.getUserId(token);
        System.out.println(userId);
        String username = JWTHelper.getUsername(token);
        System.out.println(username);
    }
}
